package com.marmot.cloud.framework.core.filter;

import cn.hutool.json.JSONUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Arrays;

public class HttpServletRequestReplacedFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;

        // 使用自定义的HttpServletRequestWrapper来包装原始的HttpServletRequest对象，以便获取请求体数据
        HttpServletRequestWrapper requestWrapper = new RequestReaderHttpServletRequestWrapper(httpRequest);

        // 打印请求的相关信息
        System.out.println("Request Method: " + requestWrapper.getMethod());
        System.out.println("Request URI: " + requestWrapper.getRequestURI());
        System.out.println("Request IP: " + getClientIPAddress(requestWrapper));
        System.out.println("Request Headers: " + getRequestHeaders(requestWrapper));
        System.out.println("Cookies: " + getCookies(requestWrapper));
        System.out.println("Request Query Parameters: " + getRequestQueryParams(requestWrapper));
        System.out.println("Form Data: " + getFormData(requestWrapper));
        System.out.println("Request Body: \n" + getRequestBody(requestWrapper)); // 获取JSON格式的请求体

        // 继续处理请求
        chain.doFilter(requestWrapper, response);
    }

    // 获取客户端 IP 地址
    private String getClientIPAddress(HttpServletRequest request) {
        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }
        return ipAddress;
    }

    // 获取请求头信息
    private String getRequestHeaders(HttpServletRequest request) {
        StringBuilder headers = new StringBuilder();
        request.getHeaderNames().asIterator().forEachRemaining(headerName ->
                headers.append(headerName).append(": ").append(request.getHeader(headerName)).append(", "));
        return headers.toString();
    }

    // 获取 Cookies
    private String getCookies(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            return "";
        }
        StringBuilder cookiesString = new StringBuilder();
        for (Cookie cookie : cookies) {
            cookiesString.append(cookie.getName()).append(": ").append(cookie.getValue()).append(", ");
        }
        return cookiesString.toString();
    }

    // 获取请求的 query_params
    private String getRequestQueryParams(HttpServletRequest request) {
        StringBuilder queryParams = new StringBuilder();
        request.getParameterMap().forEach((key, value) ->
                queryParams.append(key).append(": ").append(Arrays.toString(value)).append(", "));
        return queryParams.toString();
    }

    // 获取 form_data
    private String getFormData(HttpServletRequest request) {
        StringBuilder formData = new StringBuilder();
        request.getParameterMap().forEach((key, value) ->
                formData.append(key).append(": ").append(Arrays.toString(value)).append(", "));
        return formData.toString();
    }

    // 获取 JSON 格式的请求体信息
    private String getRequestBody(HttpServletRequest request) {
        StringBuilder body = new StringBuilder();
        try {
            BufferedReader reader = request.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                body.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 使用 Hutool 工具库的 JSONUtil 进行 JSON 格式化
        return JSONUtil.formatJsonStr(body.toString());
    }

    // 其他方法保持不变

    @Override
    public void destroy() {
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }
}
